import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_details_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/provider/erp_info.dart';
import 'package:xiongan_app_yy/utils/image_utils.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_exhibition_card_widget.dart';

//配送预约详情展示页
class DeliveryListDetailsPage extends StatefulWidget {
  final Map<String, dynamic> args;
  DeliveryListDetailsPage(this.args);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _DeliveryListDetailsPage();
  }
}

class _DeliveryListDetailsPage extends State<DeliveryListDetailsPage> {
  var _futureBuilderFuture;
  List<ImageCard> imgList = List();
  InvListDetailsEntity entity;
  dynamic reason;
  String stringQR;
  String string0;
  String string1;
  String string2;
  String string3;
  String string4;
  String string5;
  String string6;
  String path;
  bool visibility=true;

  String data;
  String cancelText="";
  bool cancelButtonHide=true;

  @override
  void initState() {
    super.initState();
    if (widget.args["state"] == "未审核") {
      cancelText="撤回预约";
      cancelButtonHide=false;
    } else if (widget.args["state"] == "审核通过") {
      cancelText="";
      cancelButtonHide=true;
    }else if (widget.args["state"] == "审核未通过") {
      cancelText = "重新预约";
      cancelButtonHide = false;
    }else if (widget.args["state"] == "已废弃") {
      cancelText = "重新预约";
      cancelButtonHide = false;
    }
    String id = widget.args["id"];
    path = "OMSWarehouseOutTask/$id";
    _futureBuilderFuture = getData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: Text("配送预约详情", style: TextStyle(fontSize: 18)),
        leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
      ),
      backgroundColor: Color(0xf4f4f4f4),
      body: FutureBuilder(
        builder: _buildFuture,
        future: _futureBuilderFuture,
      ),
    );
  }

  ///snapshot就是_calculation在时间轴上执行过程的状态快照
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    data = snapshot.data.toString();
    Map<String, dynamic> dataMap = jsonDecode(data);
    if (dataMap["WarehouseOutTask"]["flag"] == "success") {
      entity =
          InvListDetailsEntity.fromJson(dataMap["WarehouseOutTask"]["datas"]);
      if (dataMap["TaskApproval"]["datas"] != null) {
        reason = dataMap["TaskApproval"]["datas"]["remark"];
      }
      print(entity.datas.erpno);
      Provider.of<ErpInfo>(context).setData(entity.datas);
      stringQR = entity.datas.erpno;
      string0 = entity.datas.erpno;
      string1 = entity.datas.biddingbatches;
      string2 = entity.datas.projectname;
      string3 = entity.datas.taskname;
      string4 = entity.datas.projectno;
      string5 = entity.datas.destination;
      string6 = entity.datas.applytime.substring(0, 10);
      if (entity.datas.imgList.length > 0) {
        if (imgList.length == 0) {
          for (int i = 0; i < entity.datas.imgList.length; i++) {
            imgList.add(ImageCard(entity.datas.imgList.elementAt(i).imgstr));
          }
          visibility = false;
        }
      } else {
        visibility = true;
      }
    }
    return Column(
      children: <Widget>[
        Offstage(
          offstage: visibility,
          child: Container(
            height: 86,
            width: double.infinity,
            margin: EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(color: Colors.white),
            child: Scrollbar(
                child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: imgList,
              ),
            )),
          ),
        ),
        Expanded(
          child: Container(
            width: MediaQuery.of(context).size.width,
            color: Colors.white,
            child: Column(
              children: <Widget>[
                Container(
                  height: 180,
                  padding: EdgeInsets.all(25),
                  child: Center(
                    child: QrImage(
                      data: stringQR,
                      version: QrVersions.auto,
                    ),
                  ),
                ),
                Expanded(
                  child: Scrollbar(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: Column(
                        children: <Widget>[
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "领料单号",
                              exhibitionText: string0),
                          Offstage(
                              offstage:
                                  dataMap["TaskApproval"]["datas"] == null,
                              child: TextExhibitionCardWidget(
                                  distance: EdgeInsets.only(
                                      right: 15, left: 15, bottom: 16, top: 16),
                                  title: "原因",
                                  exhibitionText: reason ?? "无")),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "批次号",
                              exhibitionText: string1 ?? ""),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "项目名称",
                              exhibitionText: string2 ?? ""),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "任务名称",
                              exhibitionText: string3 ?? ""),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "编号",
                              exhibitionText: string4 ?? ""),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "目的地",
                              exhibitionText: string5 ?? ""),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "预计送达时间",
                              exhibitionText: string6 ?? ""),
                          TextCardWidget(
                              onPressed: () {
                                //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                                Navigator.pushNamed(context, "/storageDetails",
                                    arguments: {
                                      "type": "pull",
                                      "title": "配送物资明细"
                                    });
                              },
                              title: "物资明细",
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffdddddd)),
                                  top: BorderSide(
                                      width: 1, color: Color(0xffdddddd))))
                        ],
                      ),
                    ),
                  ),
                ),
                Offstage(offstage:cancelButtonHide ,child: Container(
                  width: double.infinity,
                  height: 48,
                  child: FlatButton(
                    color: Color(0XFF00A5F1),
                    child: Text(
                      cancelText,
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: _cancel,
                  ),
                )
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  void _cancel() {
    if(cancelText=="重新预约"){
        Navigator.pushNamed(context, "/delivery_list_page_new",arguments:{"bean":entity}).then((value){
          if (value == "ok") {
            Navigator.pop(context,"ok");
          }
        });
    }else if(cancelText=="撤回预约"){
      InternetAPI.getInstance()
          .get("OMS/MiWarehouseInTask/DeleteMiWarehouseInTask", (data) {
        if(data==true){
          TostUtil.showToast("撤回成功");
          Navigator.pop(context,"ok");
        }
      }, params: {
        'id': entity.datas.id,
        'operaterUserId': DataSingleton().Data.id,
        'operaterUserName': DataSingleton().Data.username,
        'tenantId': DataSingleton().Data.tenantId,
      });

    }

  }

  Future getData() async {
    var response = InternetAPI.getInstance().dio.get(
          path,
        );
    return response;
  }
}

class ImageCard extends StatefulWidget {
  final String asetImg;
  ImageCard(this.asetImg) : assert(asetImg != null);

  @override
  State<StatefulWidget> createState() {
    return ImageCardState();
  }
}

class ImageCardState extends State<ImageCard> {
  String image = "";
  @override
  void initState() {
    print("去下载");
    ImageDownloadUtil.getImageBase64(widget.asetImg, (data) {
      print("下载完成");
      setState(() {
        image = data;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        margin: EdgeInsets.all(6), child: ImageDownloadUtil.isImageType(image));
  }
}
